/**
 * 元素拖拽组件
 * @example <div v-drag></div>
 */

export default {
  //注册局部组件指令
  directives: {
    drag: function(el) {
      let dragBox = el; //获取当前元素
      //
      let minLeft = 0;
      let minTop = 0;

      let elWidth = dragBox.getBoundingClientRect().width;
      let elHeight = dragBox.getBoundingClientRect().height;

      let maxLeft = document.body.scrollWidth - elWidth;
      let maxTop = document.body.scrollHeight - elHeight;

      dragBox.onmousedown = e => {
        //算出鼠标相对元素的位置
        let disX = e.clientX - dragBox.offsetLeft;
        let disY = e.clientY - dragBox.offsetTop;
        /*console.log("drag ... ",{x:e.clientX, y:e.clientY}
                , {x:dragBox.offsetLeft,y:dragBox.offsetTop}
                , {x:maxLeft,y:maxTop}
                , {x:elWidth,y:elHeight}
                ,dragBox
                )*/
        document.onmousemove = e => {
          //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
          let left = e.clientX - disX;
          let top = e.clientY - disY;
          if (left < minLeft) {
            left = minLeft;
          }
          if (top < minTop) {
            top = minTop;
          }
          if (left > maxLeft) {
            left = maxLeft;
          }
          if (top > maxTop) {
            top = maxTop;
          }
          //移动当前元素
          dragBox.style.left = left + "px";
          dragBox.style.top = top + "px";
        };
        document.onmouseup = e => {
          e;
          //鼠标弹起来的时候不再移动
          document.onmousemove = null;
          //预防鼠标弹起来后还会循环（即预防鼠标放上去的时候还会移动）
          document.onmouseup = null;
        };
      };
    }
  }
};
